package com.kizuki.redis;

import lombok.AllArgsConstructor;

import java.util.BitSet;

public class MyBloomFilter {

    private static final int SIZE = 2 << 24;
    private static final int[] SEEDS = new int[]{3, 5, 12, 8, 9, 21};

    /**
     * 位数组
     */
    private BitSet bits = new BitSet(SIZE);

    /**
     * 存放哈希方法的数组
     */
    private simpleHash[] func = new simpleHash[SEEDS.length];

    public MyBloomFilter() {
        for (int i = 0; i < func.length; i++) {
            func[i] = new simpleHash(SIZE, SEEDS[i]);
        }
    }

    public void add(Object o) {
        for (simpleHash f : func) {
            bits.set(f.hash(o), true);
        }
    }

    public boolean contains(Object o) {
        for (simpleHash f : func) {
            if (!bits.get(f.hash(o))) {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String value1 = "https://javaguide.cn/";
        String value2 = "https://github.com/Snailclimb";
        MyBloomFilter filter = new MyBloomFilter();
        System.out.println(filter.contains(value1));
        System.out.println(filter.contains(value2));
        filter.add(value1);
        filter.add(value2);
        System.out.println(filter.contains(value1));
        System.out.println(filter.contains(value2));
    }


    @AllArgsConstructor
    private static class simpleHash{
        private int cap;
        private int seed;

        public int hash(Object value){
            int h;
            return (value == null) ? 0 : Math.abs(seed * (cap - 1) & ((h = value.hashCode()) ^ (h >>> 16)));
        }
    }
}
